const fs = require('fs'),
  path = require('path'),
  sizeList = [14, 12, 16, 18, 20]

/**
 * 从 sizeList 查找与 n 最接近的 size
 * @param {*} n
 */
function findClosestSize (size) {
  let num = sizeList[0]
  for (let i = 1; i < sizeList.length; i++) {
    if (Math.abs(size - sizeList[i]) < Math.abs(size - num)) {
      num = sizeList[i]
    }
  }
  return num
}

function _replaceFontSize (dir, excludes) {
  fs.readdirSync(dir).forEach(file => {
    let filePath = path.join(dir, file)
    if (filePath.indexOf('node_modules') > -1) {
      return
    }
    if (excludes.find(exclude => filePath.indexOf(exclude) > -1)) {
      return
    }
    if (fs.statSync(filePath).isDirectory()) {
      _replaceFontSize(filePath, excludes)
      return
    }
    if (path.extname(filePath) === '.vue') {
      let content = fs.readFileSync(filePath, 'utf8')
      content = content.replace(/font-size:\s?\d+px;/, (match, p1) => {
        let size = parseInt(match.match(/\d+/)[0])
        let n_size = findClosestSize(size)
        if (size == 14) {
          return match.replace(/\d+px/, 'var(--font-size-def)')
        }
        if (n_size == size) {
          return match.replace(/\d+px/, `var(--font-size-${size})`)
        }
        if (n_size > size) {
          return match.replace(/\d+px/, `calc(var(--font-size-${n_size}) - ${n_size - size}px)`)
        }
        if (n_size < size) {
          return match.replace(/\d+px/, `calc(var(--font-size-${n_size}) + ${size - n_size}px)`)
        }
      })
      console.log('替换文件: ', filePath)
      fs.writeFileSync(filePath, content, 'utf8')
    }
  })
}

module.exports = function replaceFontSize (options) {
  options.forEach(option => {
    _replaceFontSize(option.dir, option.excludes)
  })
}
